from State import State
from os.path import isfile
from config import get_config
import time
from calcPower import *

if isfile("./config.py"):
    from config import get_config

others_datas = get_config()["others"]
pv_datas = get_config()["PV"]


class Mode_OpenLoop(State):
    def handle(self, fsm):
        if self.pf.create_pv(pv_datas["启动开关"]).get() == 1:
            if (
                others_datas["开环功率范围"][0]
                <= self.pf.create_pv(pv_datas["开环功率设置"]).get()
                <= others_datas["开环功率范围"][1]
            ):
                print("设定闭环功率为[{}-{}]".format(*others_datas["开环功率范围"]))
                print(
                    "当前闭环功率设定为{}".format(self.pf.create_pv(pv_datas["开环功率设置"]).get())
                        
                    )
                self.pf.create_pv(pv_datas["幅度驱动"]).put(calc_Power_to_AI(self.pf.create_pv(pv_datas["开环功率设置"]).get()))
                time.sleep(3)
                if self.pf.create_pv(pv_datas["Channel"]).get() == 0:
                    self.pf.create_pv(pv_datas["幅度设定点"]).put(
                        self.pf.create_pv(pv_datas["RF_IN1"]).get()
                    )
                else:
                    self.pf.create_pv(pv_datas["幅度设定点"]).put(
                        self.pf.create_pv(pv_datas["RF_IN3"]).get()
                    )
                return fsm.mode_closeloop
            else:
                print("设定功率不在设定范围内")
                return self
        else:
            print("等待开环")
            return self
